package com.ys.controller.api.finance;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.ys.entity.hr.ThrOperateCompanyApply;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.bo.dto.NameValueDto;
import com.ys.config.MenuId;
import com.ys.entity.finance.TcwDepositPlatform;
import com.ys.entity.finance.TcwPaymentReturn;
import com.ys.entity.finance.TcwPaymentReturnItem;
import com.ys.entity.sys.TbCompanyInfo;
import com.ys.entity.sys.TbStaticConfig;
import com.ys.entity.sys.TsUserChange;
import com.ys.entity.sys.YsCol;
import com.ys.service.finance.TcwPaymentReturnService;
import com.ys.service.sys.CommonApiService;
import com.ys.service.sys.PdfService;
import com.ys.service.sys.UploadService;
import com.ys.util.DateUtil;
import com.ys.util.ExportExcelUtils;
import com.ys.util.admin.ConditionUtil;
import com.ys.util.shiro.ShiroUtils;
import com.ys.vo.LayuiTableVoJA;
import com.ys.vo.R;

/**
 * 预付款退回申请
 */
@Controller
@RequestMapping("/api/inter/tcwPaymentReturn")
public class ApiInterTcwPaymentReturnController {
    private static final Logger logger = LoggerFactory.getLogger(ApiInterTcwPaymentReturnController.class);

    @Autowired
    private CommonApiService<TcwPaymentReturn> commonApiService;

    @Autowired
    private TcwPaymentReturnService tcwPaymentReturnService;

    @Autowired
    private PdfService pdfService;


    @RequiresPermissions("tcwPaymentReturn:view")
    @RequestMapping("/search")
    @ResponseBody
    public LayuiTableVoJA search(@ModelAttribute TcwPaymentReturn cond,String conditions){
        String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
        if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
            cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
        }
        cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
        .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                 .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
        .addLeftJoin("TCW_PaymentReturnItem tpri ON tpri.paymentReturnBid = A.Bid ")//预付款退回申请子件
                .addField("tpri.thAmount AS thAmount, tpri.vJyLx AS vJyLx,tpri.status statusZj,tpri.executionTime")
        .addLeftJoin("THR_OperateCompanyBankInfo ocbi ON ocbi.id = tpri.companyBankId")//银行账户
                .addField("ocbi.vyhzhmc AS vyhzhmc,ocbi.vkhh AS vkhh,ocbi.vyhzh AS vyhzh")
        .addLeftJoin("THR_OperateCompanyApply THRO ON THRO.vgsbm = ocbi.vgsbm")//运营公司
                .addField("THRO.vgsjc AS vgsjc,THRO.CUser AS cUser,THRO.vgsbm AS vgsbm")
        ;
        cond = commonApiService.dataAuth(MenuId.TCW_PaymentReturn, cond);
        return commonApiService.searchLay(cond);
    }


    /**
     * 新增
     */
    @RequiresPermissions("tcwPaymentReturn:add")
    @RequestMapping("/toAdd")
    @ResponseBody
    public R toAdd(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("预付款退回申请新增传参：" + params);
            //修改
            return tcwPaymentReturnService.add(params,subData);
        } catch (Exception e) {
            logger.error("预付款退回申请新增出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 修改
     */
    @RequiresPermissions("tcwPaymentReturn:add")
    @RequestMapping("/toEdit")
    @ResponseBody
    public R toEdit(HttpServletRequest request, @RequestParam Map<String, Object> params,String subData
    ) {
        try {
            logger.info("预付款退回申请修改传参：" + params);
            //修改
            return tcwPaymentReturnService.edit(params,subData);
        } catch (Exception e) {
            logger.error("预付款退回申请修改出错：", e.getMessage(), e);
            return R.error(e.getMessage());
        }
    }

    @RequiresPermissions("tcwPaymentReturn:add")
    @PostMapping("/flowPass")
    @ResponseBody
    public R flowPass(HttpServletRequest request, Long id){
        try {
            return tcwPaymentReturnService.flowPass(id, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("预付款退回申请审批出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转退回
     */
    @RequiresPermissions("tcwPaymentReturn:add")
    @PostMapping("/flowRefuse")
    @ResponseBody
    public R flowRefuse(HttpServletRequest request, Long id, String reason){
        try {
            return tcwPaymentReturnService.flowRefuse(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("预付款退回申请退回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 流转驳回
     */
    @RequiresPermissions("tcwPaymentReturn:add")
    @PostMapping("/flowInit")
    @ResponseBody
    public R flowInit(HttpServletRequest request, Long id, String reason){
        try {
            return tcwPaymentReturnService.flowInit(id, reason, ShiroUtils.getUserId());
        } catch (Exception e) {
            logger.error("预付款退回申请驳回出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }

    /**
     * 删除
     */
    @RequiresPermissions("tcwPaymentReturn:add")
    @RequestMapping("/toDel")
    @ResponseBody
    public R del(HttpServletRequest request, Long id){
        try {
            return tcwPaymentReturnService.del(id);
        } catch (Exception e) {
            logger.error("删除预付款退回申请出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }


    /**
     * 导出
     */
    @RequestMapping("/export")
    @ResponseBody
    public R export(@ModelAttribute TcwPaymentReturn cond, String conditions){
        try {
            cond.setPage(0).setSize(999999);
            String _ys_createUserInfo = ConditionUtil.getConditionValue(conditions, "_ys_createUserInfo");
            if (_ys_createUserInfo != null && _ys_createUserInfo.length() != 0) {
                cond.where("t2.UserId LIKE '%" + _ys_createUserInfo + "%'" + " OR  t2.UserName LIKE '%" + _ys_createUserInfo + "%'");
            }
            cond.addLeftJoin("YS_ProcInst P ON P.Bid = A.Bid ")
                    .addField("FORMAT(P.UpdateTime, 'yyyy-MM-dd hh:mm:ss') AS updateTime1")//审核时间
                    .addLeftJoin("TS_UserChange t2 on  A.CreateChangeId = t2.id")
                    .addField("CONCAT(t2.UserId,'/', t2.UserName) as _ys_createUserInfo")
                    .addLeftJoin("TCW_PaymentReturnItem tpri ON tpri.paymentReturnBid = A.Bid ")//预付款退回申请子件
                    .addField("tpri.thAmount AS thAmount, tpri.vJyLx AS vJyLx,tpri.status statusZj,tpri.executionTime")
                    .addLeftJoin("THR_OperateCompanyBankInfo ocbi ON ocbi.id = tpri.companyBankId")//银行账户
                    .addField("ocbi.vyhzhmc AS vyhzhmc,ocbi.vkhh AS vkhh,ocbi.vyhzh AS vyhzh")
                    .addLeftJoin("THR_OperateCompanyApply THRO ON THRO.vgsbm = ocbi.vgsbm")//运营公司
                    .addField("THRO.vgsjc AS vgsjc,THRO.CUser AS cUser,THRO.vgsbm AS vgsbm");
            cond = commonApiService.dataAuth(MenuId.TCW_PaymentReturn, cond);
            ;
            //获取菜单字段数据
            List<YsCol> listField = new YsCol()
                    .setMenuId(MenuId.TCW_PaymentReturn)
                    .setFrontShow(1)
                    .setOrderby("A.SortNo asc")
                    .queryList();
            //获取数据
            List<Map<String, Object>> listData = cond.queryMap();
            //处理数据
            ExportExcelUtils<TcwPaymentReturn> util = new ExportExcelUtils<>(new TcwPaymentReturn());
            String toFilePath = util.exportExcelWithDict(listData, listField, "预付款退回申请报表");
            UploadService.UploadDto dto = commonApiService.uploadLocalToServer(toFilePath);
            return R.ok(dto.getUrl());
        }catch (Exception e){
            logger.error("导出出错：",e.getMessage(),e);
            return R.error("导出失败，请稍后重试！");
        }
    }

    /**
     * 预付款申请详情调用
     * @return
     */
    @RequestMapping("/searchWl")
    @ResponseBody
    public R searchGsXq(@ModelAttribute TcwPaymentReturn cond,String conditions){
        List<Map<String, Object>> sonlist = new TcwPaymentReturnItem()
                .addLeftJoin("TCW_PaymentReturn tpr ON tpr.bid = A.PaymentReturnBid")//预付款退回申请单
                .addField("tpr.bid bid")
                .addField("A.id paymentReturnItemId,'CNH' thCurrencyCode")
                .addField("A.thAmount AS thAmount, A.vJyLx AS vJyLx, A.accountType AS accountType")
                .addLeftJoin("THR_OperateCompanyBankInfo ocbi ON ocbi.id = A.companyBankId")//银行账户
                .addField("ocbi.vyhzhmc AS vyhzhmc,ocbi.vkhh AS vkhh,ocbi.vyhzh AS vyhzh,ocbi.vlhh AS vlhh")
                .addLeftJoin("THR_OperateCompanyApply THRO ON THRO.vgsbm = ocbi.vgsbm")//运营公司
                .addField("THRO.vgsjc AS vgsjc,THRO.vgsbm AS vgsbm")
                .addField("(SELECT top 1 tdpa.Vyhzhmc  FROM TCW_DepositPlatformAccount tdpa WHERE tdpa.Vgsbm = THRO.Vgsbm) AS depositPlatformAccountCode")
                .where("tpr.status = 0 AND tpr.effectStock = 1 AND tpr.paymentReturnType = 0 AND (SELECT count(1) FROM TCW_WanliPaymentReturnItem WHERE PaymentReturnItemId = A.id) = 0")
                .queryMap();
        return  R.ok("成功",sonlist);
    }


    /**
     * 打印万里汇预付款退回
     * @param request
     * @param bid
     * @return
     * @throws Exception
     */
    @RequestMapping("/exportdy")
    @ResponseBody
    public R exportdy(HttpServletRequest request,@RequestParam("bid") String bid) throws Exception{
        //预付款退回申请
        TcwPaymentReturn tcwPaymentReturn = new TcwPaymentReturn().setBid(bid).queryFirst();
        //预付款退回申请
        TcwPaymentReturnItem tcwPaymentReturnItem = new TcwPaymentReturnItem().setPaymentReturnBid(bid).queryFirst();
        //查询系统数据
        TbStaticConfig tbStaticConfig = new TbStaticConfig().setKeyOne("wanli-mid").setKeyTwo("wanli-mid-cs").queryFirst();
        //付款账号
        TcwDepositPlatform tcwDepositPlatform = new TcwDepositPlatform().setMid(tbStaticConfig.getName()).queryFirst();
        //人员信息
        TsUserChange tsUserChange = new TsUserChange().setId(Long.valueOf(tcwPaymentReturn.getCreateChangeId())).queryFirst();
//        //人员信息
//        ThrOperateCompanyApply thrOperateCompanyApply = new ThrOperateCompanyApply().setId(Long.valueOf(sonlist.getVgsbm())).queryFirst();
        //公司
        TbCompanyInfo tbCompanyInfo = new TbCompanyInfo().setVid(tcwDepositPlatform.getCompanyVid()).queryFirst();

        BigDecimal thAmount = BigDecimal.ZERO;
        StringBuilder vJyLx = new StringBuilder();
        StringBuilder paymentAccountList = new StringBuilder();
        String paymentAccount = "";
        //子件数据
        List<Map<String, Object>> sonlist = new TcwPaymentReturnItem()
                .addLeftJoin("THR_OperateCompanyBankInfo ocbi ON ocbi.id = A.companyBankId")//银行账户
                .addField("ocbi.vyhzhmc AS vyhzhmc,ocbi.vkhh AS vkhh,ocbi.vyhzh AS vyhzh")
                .addLeftJoin("THR_OperateCompanyApply toc ON toc.vgsbm = ocbi.vgsbm")//运营公司
                .addField("toc.vgsjc AS vgsjc,toc.vgsbm AS vgsbm,toc.vgsmc AS vgsmc")
                .addLeftJoin("TCW_OperateCompanyPrepayment tocp ON  tocp.id = A.operateCompanyPrepaymentId ")
                .addField("tocp.Vid AS tkVid,tocp.Vyhzh AS tkVyhzh,tocp.Vkhh AS tkVkhh,tocp.Vyhzhmc AS tkVyhzhmc,tocp.preResAmount AS refundableAmount,tocp.id AS operateCompanyPrepaymentId")
                .setPaymentReturnBid(bid)
                .queryMap();
        String Vgsmc=null;
        for (Map<String, Object> son : sonlist){
            //退回金额合计
            thAmount = thAmount.add(new BigDecimal(son.get("thAmount").toString()));
            //付款类型拼接(;)
            vJyLx.append(son.get("vJyLx").toString());
            vJyLx.append(";");
            //收款账号拼接(;)
            paymentAccount = son.get("vyhzhmc").toString() +"/" + son.get("vyhzh").toString() + "/" + son.get("vkhh").toString();
            paymentAccountList.append(paymentAccount);
            paymentAccountList.append(";");
            Vgsmc=son.get("vgsmc").toString();
        }

        String tkVyhzhmc = tbCompanyInfo.getVname();

        if (tcwPaymentReturn.getPaymentReturnType().equals(1)) {
            tkVyhzhmc = sonlist.get(0).get("tkVyhzhmc").toString();
        }
        List<NameValueDto> listData = new ArrayList<>();
        listData.add(new NameValueDto("单据编号",bid));
        listData.add(new NameValueDto("申请人",tsUserChange.getUserId() + "/" + tsUserChange.getUserName()));
        listData.add(new NameValueDto("申请部门",tsUserChange.getRoleName()));
        if( tkVyhzhmc.equals("福州逸博供应链有限公司")) {
            listData.add(new NameValueDto("申请公司",Vgsmc));
        }
        listData.add(new NameValueDto("收款账号",paymentAccountList.toString()));
        listData.add(new NameValueDto("付款金额",thAmount.toString()));
        listData.add(new NameValueDto("付款说明",""));
        String url = pdfService.generatePDF(bid,"预付款退回申请",tkVyhzhmc,
                DateUtil.getYYYY_MM_DD_HH_mm_ss(tcwPaymentReturn.getCreateTime()),listData);
        return R.ok(url);
    }

    /**
     * 作废
     */
    @RequiresPermissions("tcwPaymentReturn:cancel")
    @PostMapping("/cancel")
    @ResponseBody
    public R cancel(String bid,Long id){
        try {
            return tcwPaymentReturnService.cancel(bid,id);
        } catch (Exception e) {
            logger.error("作废透明计划申报出错：",e.getMessage(),e);
            return R.error(e.getMessage());
        }
    }
}
